from django.shortcuts import render
from rest_framework.views import APIView
from django.http import HttpResponse
from meiduo_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
import random
import logging


from . import constants
from meiduo_mall.libs.yuntongxun.sms import CCP
from . import serializers
from celery_tasks.sms.tasks import send_sms_code
# Create your views here.


# 日志记录器
logger = logging.getLogger('django')


# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class SMSCodeView(GenericAPIView):
    # '发送短信验证码'

    # 指定序列化器
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self, request, mobile):
        # 忽略校验,假装校验通过

        # 创建序列化器对象：　data=request.query_params 是将url中的查询字符串传入到序列化器中
        serializer = self.get_serializer(data=request.query_params)
        # 开启校验
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        logger.info(sms_code)

        # 存储短信验证码到redis数据库
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # # 纪录用户发送短信的频次
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 创建管道
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 纪录用户发送短信的频次
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 开启执行
        pl.execute()

        # 发送短信验证码
        #CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], constants.SEND_SMS_TEMPLATE_ID)
        # 调用异步任务，将异步任务发送到broker任务队列中
        # 使用delay函数
        send_sms_code.delay(mobile, sms_code)


        # 响应结果
        return Response({'message':'OK'})



# url('^image_codes/(?P<image_code_id>[\w-]+)/$', views.ImageCodeView.as_view()),
class ImageCodeView(APIView):
    '''提供图片验证码'''
    def get(self, request, image_code_id):
        # 生成图片验证码:text是验证码内容，需要保存到Redis, image是图片验证码数据，需要响应给前段
        text, image = captcha.generate_captcha()

        # 将图片验证码内容存储到redis数据库
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setsx('key','expires','value')
        redis_conn.setex('img_%s'%image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 将图片验证码图片数据响应到前段
        return HttpResponse(image, content_type='image/jpg')


